package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class combinationSum3 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        backtrack(k, 1, 0, n);
        return result;
    }
    public void backtrack(int k, int startIndex, int sum, int targetSum){
        if (sum > targetSum){
            return;
        }
        if (path.size() == k && sum == targetSum){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= 9 - (k-path.size())+1; i++) {
            path.add(i);
            sum += i;
            backtrack(k, i + 1, sum, targetSum);
            path.removeLast();
            sum -= i;
        }
    }
}
